var express = require('express');
var router = express.Router();
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const UserModel = require('../models/UserModel');
var logger = require('morgan');

/* GET home page. */
router.get('/', function (req, res) {
  res.render('index', { title: 'notebook' });
});

/**
 * 登录用户
 */
router.get('/login', function (req, res) {
  res.render('auth/login');
});
router.post('/login', function (req, res) {
  let { username, password } = req.body;
  //console.log(username);
  //console.log(password);
  UserModel.findOne(
    { username: username, password: md5(password) },
    (err, data) => {
      if (err) {
        res.status(500).send('登录, 请稍后再试~~ ');
        return;
      }
      //判断data
      if (!data) {
        es.render('success', { msg: '登陆失败', url: '/auth/login' });

        return;
      }
      //写入session
      req.session.username = data.username;
      req.session_id = data._id;
      //响应成功
      //登录成功响应
      res.render('success', { msg: '登录成功', url: '/account' });
    }
  );
});

/**
 * 用户注册
 */
router.get('/reg', function (req, res) {
  res.render('auth/reg');
});
router.post('/reg', function (req, res) {
  let { username, password } = req.body;
  //console.log(username);
  //console.log(password);
  UserModel.create(
    { username: username, password: md5(password) },
    (err, data) => {
      if (err) {
        return res.json({
          code: '0001',
          msg: '数据库读取失败',
          data: null,
        });
      }
      //判断data
      if (!data) {
        return res.json({
          code: '0003',
          msg: '插入失败',
          data: null,
        });
      }
      //响应成功
      //注册成功
      res.render('success', { msg: '注册成功', url: '/login' });
    }
  );
});
//退出登录
//退出登录
router.post('/logout', (req, res) => {
  //销毁 session
  req.session.destroy(() => {
    res.render('success', {msg: '退出成功', url: '/login'});
  })
});

module.exports = router;
